package current.aqs;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;

public class PhaserUseDemo {
    Phaser phaser = new Phaser();

    ExecutorService executorService = Executors.newCachedThreadPool();

    class Worker implements Runnable {
        @Override
        public void run() {
            // 4个worker工作 + 主线程同步 作一次周期
            phaser.register();
            while (true) {
                try {
                    TimeUnit.MILLISECONDS.sleep(500);
                    // 打印当前阶段的编号
                    System.out.println("工作... " + phaser.getPhase());
                    phaser.arriveAndAwaitAdvance();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void run() {
        // main thread
        phaser.register();

        for (int i = 0; i < 4; i++) {
            executorService.execute(new Worker());
        }

        while (true) {
            phaser.arriveAndAwaitAdvance();
            System.out.println("同步..." + phaser.getPhase());
        }
    }

    public static void main(String[] args) {
        PhaserUseDemo phaserUseDemo = new PhaserUseDemo();
        phaserUseDemo.run();
    }
}
